//
//  LWZFMPlayViewController.m
//  MusicFM
//
//  Created by 王景欣 on 16/1/14.
//  Copyright © 2016年 LWZ. All rights reserved.
//

#import "LWZFMPlayViewController.h"
#define FMPlayWIDTH [UIScreen mainScreen].bounds.size.width / 375
#define FMPlayHEIGHT [UIScreen mainScreen].bounds.size.height / 667


@interface LWZFMPlayViewController ()<AVAudioPlayerDelegate>

@property (nonatomic, strong) UIView *rotatingView;
@property (nonatomic, strong) UIImageView *rotatingImageView;

@property (nonatomic, strong) UIButton *startButton;
@property (nonatomic, strong) UIButton *beforeButton;
@property (nonatomic, strong) UIButton *nextButton;

@property (nonatomic, strong) STKDataSource *sktDataSource;
@property (nonatomic, strong) STKAudioPlayer *player;
@property (nonatomic, strong) ZFProgressView *picTiao;

//定时器
@property (nonatomic, strong) NSTimer *playTimer;
//---
@property(nonatomic,assign)NSInteger uid;

@end

@implementation LWZFMPlayViewController

#pragma mark - 单例
+ (instancetype)sharePlayerViewController {
    static LWZFMPlayViewController *playerVC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        playerVC = [[LWZFMPlayViewController alloc] init];
    });
    return playerVC;
}
//播放开始时
- (void) audioPlayer:(STKAudioPlayer *)audioPlayer didStartPlayingQueueItemId:(NSObject *)queueItemId {
}
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer logInfo:(NSString *)line {
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState {
}
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode {
}
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject *)queueItemId {
}
#pragma mark - viewWillAppear
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    if (self.player.state == STKAudioPlayerStatePlaying) {
        
        [self.startButton setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
    }else if (self.player.state == STKAudioPlayerStatePaused) {
        
        [self.startButton setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
    }

}
#pragma mark - ViewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor colorWithRed:(244 / 255.0) green:(0 / 255.0) blue:(89 / 255.0) alpha:1.0];
    
    [self creatRotatingView];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(16, 24, 20, 20);
    [backButton setImage:[UIImage imageNamed:@"arrowdown"] forState:UIControlStateNormal];
    backButton.backgroundColor = [UIColor colorWithWhite:1 alpha:0.8];
    backButton.layer.cornerRadius = 10;
    backButton.layer.masksToBounds = YES;
    [backButton addTarget:self action:@selector(handleDismissAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    
    [self creatButton];
//    //来电打断播放器
//    // 1. 创建音频会话
//    AVAudioSession *session = [AVAudioSession sharedInstance];
//    // 2. 设置会话类型
//    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
//    // 3. 激活会话
//    [session setActive:YES error:nil];
//    
//    [[UIApplication sharedApplication]beginReceivingRemoteControlEvents];
//    //监听
//    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopPlayer:) name:@"stop" object:nil];
    
    self.player = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions) {
        .flushQueueOnSeek = YES, .enableVolumeMixer = YES,.equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000}
    }];
    //下面的初始化也可以,但设置不了enableVolumeMixer,就无法调节音量
    //self.player = [[STKAudioPlayer alloc] init];
    self.player.volume = 0.4;

    [self imageProgressTiao];

}
- (void)handleData {
    //http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=
    NSString *stringUrl = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%ld", self.song_id];
    [MHNetWorkTask getWithURL:stringUrl withParameter:nil withHttpHeader:nil withResponseType:ResponseTypeJSON withSuccess:^(id result) {
        NSLog(@"%@", result);
//        LWZHostPlayModel *playData = [[LWZHostPlayModel alloc] initWithDataSource:result];
        LWZPlayModel *playData = [[LWZPlayModel alloc] initWithDataSource:result];
        [self.player play:playData.playUrl64];
        [self.rotatingImageView yy_setImageWithURL:[NSURL URLWithString:playData.coverLarge] placeholder:[UIImage imageNamed:@"12408408,2880,1800"]];
        [self.rotatingImageView yy_setImageWithURL:[NSURL URLWithString:playData.coverLarge] options:YYWebImageOptionProgressiveBlur];
        self.uid = playData.uid;
        
        //创建定时器
        self.playTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(trackTime) userInfo:nil repeats:YES];

    } withFail:^(NSError *error) {
        
    }];
}
#pragma mark - 定时器方法
-(void)trackTime {
    //音乐总时长
    self.progressSlider.maximumValue = self.player.duration;
    self.progressSlider.value = self.player.progress;//当前进度
    
    //当前时长
    NSInteger proMin = (NSInteger)self.player.progress/60;//当前秒
    NSInteger proSec = (NSInteger)self.player.progress%60;//当前分钟
    
    //duration 总时长
    NSInteger durMin = (NSInteger)self.player.duration/60;//总秒
    NSInteger durSec = (NSInteger)self.player.duration%60;//总分钟
    
    self.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", (long)proMin, (long)proSec, (long)durMin, (long)durSec];

}

#pragma mark - 监听是否播放
- (void)stopPlayer:(NSNotification *)stop {
    
}
#pragma mark - 返回按钮
- (void)handleDismissAction:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 创建上面的旋转的VIew
- (void)creatRotatingView {
    
    self.rotatingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight * 3 / 5)];
    self.rotatingImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    self.rotatingImageView.layer.cornerRadius = 100;
    self.rotatingImageView.layer.masksToBounds = YES;
    self.rotatingImageView.center = CGPointMake(kScreenWidth / 2, kScreenHeight * 3 / 10);
    self.rotatingImageView.backgroundColor = [UIColor clearColor];
    
    [self.rotatingView addSubview:self.rotatingImageView];
    [self.view addSubview:self.rotatingView];
    
}

- (void)creatButton {
    
    self.startButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.startButton.frame = CGRectMake(0, 0, 30, 30);
    [self.startButton setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
    [self.startButton addTarget:self action:@selector(startButtonDidPress:) forControlEvents:UIControlEventTouchUpInside];
    self.startButton.center = CGPointMake(kScreenWidth / 2, kScreenHeight * 4 / 5);
    [self.view addSubview:self.startButton];
    
    self.beforeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.beforeButton.frame = CGRectMake(0, 0, 30, 30);
    [self.beforeButton setImage:[UIImage imageNamed:@"rewind"] forState:UIControlStateNormal];
    [self.beforeButton addTarget:self action:@selector(beforeButtonDidPress:) forControlEvents:UIControlEventTouchUpInside];
    self.beforeButton.center = CGPointMake(kScreenWidth / 4, kScreenHeight * 4 / 5);
    [self.view addSubview:self.beforeButton];
    
    self.nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nextButton.frame = CGRectMake(0, 0, 30, 30);
    [self.nextButton setImage:[UIImage imageNamed:@"forward"] forState:UIControlStateNormal];
    [self.nextButton addTarget:self action:@selector(nextButtonDidPress:) forControlEvents:UIControlEventTouchUpInside];
    self.nextButton.center = CGPointMake(kScreenWidth * 3 / 4, kScreenHeight * 4 / 5);
    [self.view addSubview:self.nextButton];
}
#pragma mark - 控件button的点击事件
- (void)startButtonDidPress:(UIButton *)sender {
    if (self.player.state == STKAudioPlayerStatePlaying) {
        [self.player pause];
        [self.playTimer invalidate];
        [self.startButton setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
        
    }else if (self.player.state == STKAudioPlayerStatePaused) {
        [self.player resume];
        [self.startButton setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
    }else {
        [self handleData];
    }
    sender.selected = !sender.selected;

}
- (void)beforeButtonDidPress:(UIButton *)sender {
    NSLog(@"self.indexRow == %ld",self.indexRow);
    if (self.indexRow!= 0) {
        
        self.indexRow = (self.indexRow-1);
    }
    else {
        sender.enabled = NO;
    }
    LWZPlayModel * play = [self.allMusicArray objectAtIndex:self.indexRow];
    self.song_id = play.trackId;

    
}
//歌曲id 系统方法
-(void)setSong_id:(NSInteger)song_id {
    _song_id = song_id;
    if (song_id == 0) {
        
    }else {
        [self handleData];
    }
    if (_indexRow == 0) {
        self.beforeButton.enabled = NO;
    }
    
}

- (void)nextButtonDidPress:(UIButton *)sender {
    //+1后对总数取余，防止多次点击， 数组越界
    if (self.allMusicArray.count == 0) {
        [self handleData];
    }else {
        self.indexRow = (self.indexRow + 1)%self.allMusicArray.count;
        
        if (self.indexRow<self.allMusicArray.count) {
            LWZPlayModel * singleM = [self.allMusicArray objectAtIndex:self.indexRow];
            self.song_id = singleM.trackId;
        }else {
            [self handleData];
        }
        self.startButton.enabled = YES;
    }
}

#pragma mark - 图片进度条
- (void)imageProgressTiao {
    self.picTiao = [[ZFProgressView alloc] initWithFrame:CGRectMake(0, 0, 210, 210)];
    self.picTiao.center = CGPointMake(kScreenWidth / 2, kScreenHeight * 3 / 10);
    self.picTiao.backgroundColor = [UIColor clearColor];
    self.picTiao.progressStrokeColor = [UIColor greenColor];
    [self.rotatingView addSubview:self.picTiao];
}

#pragma mark - ——————————————————————————
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
